<template>
  <a-form
    ref="formRef"
    :model="formState"
    :rules="rules"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
  >
    <a-form-item ref="username" label="用户名">
      <a-input v-model:value="formState.username" />
    </a-form-item>
    <a-form-item ref="userAccount" label="账号" name="userAccount">
      <a-input v-model:value="formState.userAccount" />
    </a-form-item>
    <a-form-item ref="userPassword" label="密码" name="userPassword">
      <a-input v-model:value="formState.userPassword" type="password" />
    </a-form-item>
    <a-form-item ref="email" label="邮箱">
      <a-input v-model:value="formState.email" />
    </a-form-item>
    <a-form-item ref="phone" label="手机号">
      <a-input v-model:value="formState.phone" />
    </a-form-item>
    <a-form-item label="性别">
      <a-radio-group v-model:value="formState.gender">
        <a-radio value="1">男</a-radio>
        <a-radio value="0">女</a-radio>
        <a-radio value="other">其他</a-radio>
      </a-radio-group>
    </a-form-item>
    <a-form-item label="头像">
      <!-- <a-upload list-type="picture-card"> -->

      <!-- <input type="file" @click="onFileChange" style="height: 50px;width: 50px;border: 1px dashed #D9D9D9;display: flex;justify-content: center;align-items: center;"/>
          <PlusOutlined /> -->
      <div style="display: flex">
        <div v-if="imageData" style="margin-right: 10px" class="image-container">
          <img
            :src="imageData"
            alt="Selected Image"
            style="height: 50px;width: 50px margin-top: 10px"
          />
          <button class="delete-button" @click="removeImage">删除</button>
        </div>
        <div class="file-input-container">
          <input type="file" class="file-input" @change="onFileChange" />
        </div>
      </div>

      <!-- </a-upload> -->
    </a-form-item>
    <a-form-item label="用户状态">
      <a-select v-model:value="formState.userStatus" placeholder="请选择用户状态">
        <a-select-option value="active">在线</a-select-option>
        <a-select-option value="inactive">离线</a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="角色">
      <a-select v-model:value="formState.userRole" placeholder="请选择用户角色">
        <a-select-option value="admin">管理员</a-select-option>
        <a-select-option value="user">用户</a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item label="创建时间">
      <a-input v-model:value="formState.createTime" disabled />
    </a-form-item>
    <a-form-item label="更新时间">
      <a-input v-model:value="formState.updateTime" disabled />
    </a-form-item>
    <a-form-item label="是否删除" name="isDelete">
      <a-switch v-model:checked="formState.isDelete" checked-children="1" un-checked-children="0" />
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" @click="onSubmit" :disabled="tmp">提交</a-button>
      <a-button style="margin-left: 10px" @click="resetForm">Reset</a-button>
    </a-form-item>
  </a-form>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, toRaw } from 'vue';
import type { Ref } from 'vue';
import { computed } from 'vue';
import type { Rule } from 'ant-design-vue/es/form';
import { message } from 'ant-design-vue';
import { UserOutlined, PlusOutlined } from '@ant-design/icons-vue';
import type { DataItem } from '@/type/type';
import { useRoute } from 'vue-router';
import getUsersInfo from '@/hooks/getUsers';
import { update } from '@/api/user-api/userApi';

const route = useRoute();

// interface FormState {
//   username: string;
//   userAccount: string;
//   userPassword: string;
//   avatarUrl: string;
//   gender: string;
//   phone: string;
//   email: string;
//   userStatus: string;
//   createTime: string;
//   updateTime: string;
//   isDelete: boolean;
//   userRole: string;
// }

const formRef = ref();
const labelCol = { span: 5 };
const wrapperCol = { span: 13 };
const formState: Ref<DataItem> = ref({
  id: 1,
  username: '',
  userAccount: '',
  avatarUrl: '',
  gender: 1,
  userPassword: '',
  phone: '',
  email: '',
  userStatus: 1,
  createTime: '',
  updateTime: '',
  isDelete: 0,
  userRole: 1,
});

//上传图片
const imageData = ref<string | null>(null);

const onFileChange = (event: Event) => {
  console.log('onFileChange');
  const input = event.target as HTMLInputElement;
  if (input.files && input.files[0]) {
    const file = input.files[0];
    const reader = new FileReader();

    reader.onload = (e: ProgressEvent<FileReader>) => {
      imageData.value = e.target?.result as string;
    };

    reader.readAsDataURL(file);
  }
};
const removeImage = () => {
  imageData.value = null; // 移除图片
};

onMounted(async () => {
  formState.value = await getUsersInfo(String(route.query.param));
  imageData.value=formState.value.avatarUrl;
});
//验证通过激活按钮
let tmp = computed(() => {
  return formState.value.userAccount.length >= 4 && formState.value.userPassword.length >= 8
    ? false
    : true;
});
//验证必输入项
const rules: Record<string, Rule[]> = {
  userAccount: [
    { required: true, message: '请输入账号', trigger: 'change' },
    { min: 4, message: '账号最少输入4位', trigger: 'change' },
  ],
  userPassword: [
    { required: true, message: '请输入密码', trigger: 'change' },
    { min: 8, message: '密码最少输入8位', trigger: 'change' },
  ],
};
//提交
const onSubmit = async () => {
  formState.value.avatarUrl = imageData.value + '';
  formState.value.isDelete = formState.value.isDelete === true ? 1 : 0;
  const response = await update(formState.value);
  message.info(response);
  // formRef.value
  //   .validate()
  //   .then(() => {
  //     console.log('Form Values:', formState);
  //   })
  //   .catch(error => {
  //     console.log('Validation Error:', error);
  //   });
};

const resetForm = () => {
  formRef.value.resetFields();
};
</script>
<style lang="less" scoped>
.file-input-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  border: 2px dashed #ccc; /* 虚线边框 */
  border-radius: 8px; /* 边框圆角 */
  cursor: pointer;
  position: relative;
  background-color: #f9f9f9;
  transition: background-color 0.3s ease;
}

.file-input-container:hover {
  background-color: #f0f0f0; /* 悬停时背景颜色变化 */
}

.file-input-container::before {
  content: '上传图片';
  font-size: 10px;
  color: #aaa;
  // position: absolute;
  // top: 50%;
  // left: 50%;
  // transform: translate(-50%, -50%);
}

.file-input {
  opacity: 0;
  position: absolute;
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.image-container {
  position: relative;
  display: inline-block;
  margin-right: 10px;
}

.image-preview {
  height: 50px;
  width: 50px;
  margin-top: 10px;
  display: block;
}

.delete-button {
  display: none;
  position: absolute;
  top: 0;
  right: 0;
  background-color: red;
  color: white;
  border: none;
  padding: 2px 6px;
  cursor: pointer;
  font-size: 12px;
  opacity: 0.5;
}

.image-container:hover .delete-button {
  display: block;
}
</style>